package com.learn.concurrent;

import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangxing
 * @version 2020/9/4 22:35 Administrator
 */
public class LearnReentrantLock {
    private static final int NUM = 10;
    public static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(NUM, NUM, 1, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(NUM));
    /**
     * 公平锁
     */
    public static final ReentrantLock fairSync = new ReentrantLock(true);
    /**
     * 非公平锁
     */
    public static final ReentrantLock noFairSync = new ReentrantLock(false);
    /**
     * 栅栏
     */
    public static final CyclicBarrier CYCLIC_BARRIER = new CyclicBarrier(NUM);
    public static void main(String[] args) {
        for (int i = 0; i < NUM; i++) {
            Thread thread= new Thread(()->runThreadFairSync(),"thread"+i);
            threadPoolExecutor.execute(thread);
        }
        threadPoolExecutor.shutdown();
    }
    public static void runThreadFairSync(){
        try {
            CYCLIC_BARRIER.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        fairSync.lock();
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            fairSync.unlock();
        }
    }
}
